package com.roin.learn.springsecurity.controller;


import com.roin.learn.springsecurity.dto.SysAdminLoginParam;
import com.roin.learn.springsecurity.enums.ResultCode;
import com.roin.learn.springsecurity.model.JsonResult;
import com.roin.learn.springsecurity.service.SysAdminService;
import com.roin.learn.springsecurity.util.ResultTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统管理员用户表 前端控制器
 * </p>
 *
 * @author Roin
 * @since 2021-01-07
 */
@RestController
@RequestMapping("/admin")
public class SysAdminController {
    @Autowired
    SysAdminService adminService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JsonResult login(@Validated @RequestBody SysAdminLoginParam SysAdminLoginParam) {
        String token = adminService.login(SysAdminLoginParam.getUsername(), SysAdminLoginParam.getPassword());
        if (token == null) {
            return ResultTool.fail(ResultCode.USER_CREDENTIALS_ERROR);
        }
        Map<String, String> tokenMap = new HashMap<>(2);
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return ResultTool.success(tokenMap);
    }

    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    public JsonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = adminService.refreshToken(token);
        if (refreshToken == null) {
            return ResultTool.fail(ResultCode.USER_TOKEN_EXPIRED);
        }
        Map<String, String> tokenMap = new HashMap<>(2);
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return ResultTool.success(tokenMap);
    }


    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public JsonResult logout() {
        //todo 这里是否需要将当前用户的token设置成过期？能否做到？
        return ResultTool.success(null);
    }
}
